package scct.caojintao.dao;

import scct.caojintao.model.User;
import scct.caojintao.utils.DBUtil ;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    /**
     * @param name 用户名
     * @param pass 密码
     * @return 用户对象
     */
    public User login(String name, String pass) {
        User user = null;
//        获取数据库连接对象
        Connection conn = DBUtil.getConnection();
        String sql = "select * from sm_user where username=? and password=?";
//        预编译查询对象
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, pass);
//            查询
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                int age = rs.getInt("age");
                String gender = rs.getString("gender");
                String mobile = rs.getString("mobile");
                user = new User(id,username,password,gender,age,mobile);
            }
            DBUtil.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }
}
